import { defineStore } from 'pinia'
import { ref } from 'vue'
import { product } from '../../types'

export const useCartStore = defineStore(
  'cart',
  () => {
    // 是否登录
    const login = ref(false)
    const userInfo = ref()
    const cartList = ref<product[]>([])
    const isShowCart = ref(false)

    // 展示购物车
    const showCart = (show: boolean) => {
      isShowCart.value = show
    }

    // 已登录
    const isLogin = (info: any) => {
      userInfo.value = info
      login.value = true
    }

    // 添加到购物车
    const addCart = (product: product) => {
      const { productId, salePrice, productName, productImageBig, productNum = 1 } = product
      let goods = {
        productId, salePrice, productName, productImageBig, productNum: 0
      }
      let flag = true
      // 存在物品时
      if (cartList.value.length) {
        cartList.value.forEach(item => {
          if (item.productId === productId) {
            if (item.productNum! >= 0) {
              flag = false
              item.productNum! += productNum
            }
          }
        })
      }
      // 购物车为空时
      if (!cartList.value.length || flag) {
        goods.productNum = productNum
        cartList.value.push(goods)
      }
    }


    return {
      login,
      userInfo,
      cartList,
      isShowCart,
      showCart,
      isLogin,
      addCart
    }
  },
  {
    persist: true
  }
)